package com.zoffy.catdiarybackend.websocket;


import com.alibaba.fastjson2.JSON;
import com.zoffy.catdiarybackend.service.ArticleService;
import jakarta.annotation.Resource;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
public class ArticleWebSocket implements WebSocketHandler {
    @Resource
    private ArticleService articleService;

    private final static Map<String, ArticleCollaborationHandler> clients=new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //todo 发送初始内容
        System.out.println(session.getId()+"连接了");
        String articleId =(String) session.getAttributes().get("articleId");
        clients.putIfAbsent(articleId,new ArticleCollaborationHandler(Long.parseLong(articleId),articleService));
        clients.get(articleId).addClient(session);
        OperationMessage<String> operationMessage=new OperationMessage<>();
        operationMessage.setData(null);
        operationMessage.setType("setClient");
        operationMessage.setServerId(-1);
        operationMessage.setClientId(RandomUtils.nextLong());
        session.sendMessage(new TextMessage(JSON.toJSONString(operationMessage)));

    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        String articleId =(String) session.getAttributes().get("articleId");
        ArticleCollaborationHandler articleCollaborationHandler = clients.get(articleId);
        if(message instanceof TextMessage){
            articleCollaborationHandler.handleMessage((TextMessage)message);
        }

    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        String articleId =(String) session.getAttributes().get("articleId");
        ArticleCollaborationHandler articleCollaborationHandler = clients.get(articleId);
        articleCollaborationHandler.removeClient(session);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }



}
